/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util';
import { deleteAction, getAction, putAction, postAction, httpAction, downFile, getFileAccessHttpUrl,printAction } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types"
import store from '@/store'

export const JeecgListMixin = {
    data() {
        return {
            /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
            queryParam: {
                modelCode: '',
                itemName: ''
            },
            /* 数据源 */
            dataSource: [],
            footerDataSource:[],
            //显示文字内容标识
            flag: false,
            // 显示隐藏按钮名
            showHideBom: '隐藏设计BOM',
            // 显示功能栏的标识
            funFlag: false,
            //显示隐藏设计BOM功能栏
            showHideBomFun: '隐藏功能栏',
            /* 分页参数 */
            ipagination: {
                // current: 1,
                // pageSize: 10,
                // pageSizeOptions: ['10', '20', '30'],
                current: 1,
                pageSize: 10,
                pageSizeOptions: ['10', '20', '30', '100', '200', '300', '400', '500'],
                showTotal: (total, range) => {
                    console.log('range', range);
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                showQuickJumper: true,
                showSizeChanger: true,
                total: 0,
            },
            /* 排序参数 */
            isorter: {
                column: 'createTime',
                order: 'desc',
            },
            /* 筛选参数 */
            filters: {},
            /* table加载状态 */
            loading: false,
            /* table选中keys*/
            selectedRowKeys: [],
            /* table选中records*/
            selectionRows: [],
            /* 查询折叠 */
            toggleSearchStatus: false,
            /* 高级查询条件生效状态 */
            superQueryFlag: false,
            /* 高级查询条件 */
            superQueryParams: '',
            /** 高级查询拼接方式 */
            superQueryMatchType: 'and',
        }
    },
    created() {
        // this.toggleSearchStatus == true
        // this.$bus.$on('record', (record) => { 
        //     console.log('record111---------------', record);
        //     if (record.itemName) {
        //         this.queryParam.itemName = record.itemName
        //         console.log('this.queryParam.itemName111',this.queryParam.itemName);
        //         this.searchQuery()
        //         // this.loadData();
        //     }
        // })
        if (!this.disableMixinCreated) {
            console.log(' -- mixin created -- ')
                // this.$bus.$on('record', (record) => { 
                //     console.log('record111---------------', record);
                //     if (record.itemName) {
                //         this.queryParam.itemName = record.itemName
                //         console.log('this.queryParam.itemName111',this.queryParam.itemName);
                //         // this.searchQuery()
                //         // this.loadData();
                //     }
                // })
            this.loadData();
            //初始化字典配置 在自己页面定义
            this.initDictConfig();
        }
    },
    computed: {
        //token header
        tokenHeader() {
            let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
            let tenantid = Vue.ls.get(TENANT_ID)
            if (tenantid) {
                head['tenant-id'] = tenantid
            }
            return head;
        }
    },
    methods: {
        loadData(arg) {
            if (!this.url.list) {
                this.$message.error("请设置url.list属性!")
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1;
            }
            // -----------------
            var params = this.getQueryParams(); //查询条件
            console.log("params", params);
            params.allocator = params.allocator1
            this.loading = true;
            getAction(this.url.list, params).then((res) => {
                console.log("res-----:", res);
                if (res.success) {
                    //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                    this.dataSource = res.result.records || res.result;
                    this.footerDataSource[0] = this.dataSource[0];
                    // if(this.$data.description == "报表三管理页面"){
                    //   sessionStorage.setItem('mixinData', JSON.stringify(this.dataSource)); // 将混入的数据存储到Session中
                    // }
                    // if(this.$data.description == "报表四管理页面"){
                    //     sessionStorage.setItem('mixinData2', JSON.stringify(this.dataSource)); // 将混入的数据存储到Session中
                    //   }
                    console.log("数据源",res.result.records[0])
                    console.log("res.message:",res.message)
                    this.planForm = this.dataSource
                    if (res.result.total) {
                        this.ipagination.total = res.result.total;
                    } else {
                        this.ipagination.total = 0;
                    }
                    //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
                } else {
                    this.dataSource = null;
                    this.ipagination.total = 0;
                    this.$message.warning(res.message)
                }
            }).finally(() => {
                this.loading = false
            })
        },
        //筛选表的列
        columnsCheck(checked, data, index) {
            console.log("checked, data, index:", checked, data, index);
            data[index].show = checked
        },
        // 固定显示隐藏表头
        btnShowHideBom() {
            this.flag = !this.flag
            if (this.flag == true) {
                this.showHideBom = "显示设计BOM"
                    // 根据固定表头的index隐藏设计BOM
                for (let index = 0; index < 8; index++) {
                    this.columns[index].show = false
                        // if (index == 7) {
                        //     this.columns[index + 1].width = 50
                        // }
                }

            } else if (this.flag == false) {
                this.showHideBom = "隐藏设计BOM"

                // 根据固定表头的index显示设计BOM
                for (let index = 0; index < 8; index++) {
                    this.columns[index].show = true
                        // if (index == 7) {
                        //     this.columns[index + 1].width = 50
                        // }
                }
            }
        },
        // 显示隐藏订购BOM功能栏
        btnShowFun() {
            this.funFlag = !this.funFlag
            if (this.funFlag == true) {
                this.showHideBomFun = "显示功能栏"
                    // 隐藏功能栏
                this.columns[this.columns.length - 1].show = false
            } else if (this.funFlag == false) {
                this.showHideBomFun = "隐藏功能栏"
                    // 根据固定表头的index显示设计BOM
                this.columns[this.columns.length - 1].show = true
            }

        },
        // 选择固定的表头
        // columnsCheckHeard(checked, data, index) {
        //     console.log("checked, data, index:", checked, data, index);
        //     if (checked) {
        //         if (data[index].dataIndex == 'action') {
        //             data[index].fixed = 'right'
        //         } else {
        //             data[index].fixed = 'left'
        //         }
        //     } else {
        //         data[index].fixed = ''
        //     }

        // },
        // 批量更新
        batchUpdate() {
            this.onSelectChange()
            console.log('this.onSelectChange():', this.onSelectChange());
        },
        // 表格编辑失去焦点事件 ERP
        blurpartName(e, row) {
            console.log('e', e);
            console.log('row', row);
            // ERP代码中的数据变化则更新当前行的数据
            // if (e.target.value != '') {

            putAction(this.url.pieceData, row).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    // 重新渲染页面
                    this.loadData();
                } else {
                    //this.$message.error(`序号为${row.designSerialNo}的设计BOM发生错误,错误信息：ERP代码有误，请检查！`)
                    this.$message.error(`订购序号为${row.designSerialNo}的${res.message}`)
                }

            })


            // }

            // this.planForm=JSON.parse(JSON.stringify(row));
            // this.planForm = Object.assign({}, row);
            // console.log('planForm', this.planForm);
            console.log('value', e.target.value);
        },
        handleBlur(v, row) {
            console.log('v', v)
            console.log('row', row)
            if (row.erpCode == null || row.erpCode == undefined) {
                row.erpCode = ''
            }
            if (row.mixMaterialsAndNotOrder == undefined) {
                row.mixMaterialsAndNotOrder = ''
            }
            if (row.rawMaterialsAndAccessories == undefined) {
                row.rawMaterialsAndAccessories = ''
            }
            if (row.bulkPartsType == undefined) {
                row.bulkPartsType = ''
            }
            if (row.withoutAllowanceDimension == undefined) {
                row.withoutAllowanceDimension = ''
            }
            if (row.t100DemandDate == undefined) {
                row.t100DemandDate = ''
            }

            console.log('row.bulkPartsType', row.bulkPartsType)
            console.log('row.mixMaterialsAndNotOrder', row.mixMaterialsAndNotOrder)
            console.log('row.rawMaterialsAndAccessories', row.rawMaterialsAndAccessories)
            console.log('row.withoutAllowanceDimension', row.withoutAllowanceDimension)
            console.log('row.erpCode:', row.erpCode)
            console.log('row.t100DemandDate:', row.t100DemandDate)
            if (row.erpCode != '') {

                console.log('发请求')
                    // 发请求
                putAction(this.url.pieceData, row).then((res) => {
                    console.log(res);
                    if (res.code == 200) {
                        // 重新渲染页面
                        this.loadData();
                    } else {
                        this.$message.error(`订购序号为${row.designSerialNo}的${res.message}`)
                    }

                })
            }
        },
        // 请购备注内容发送变化时刷新行高(刷新无效)
        handleChange(row) {
            if (this.showHideBom == '显示设计BOM') {
                console.log("Aa");
                for (let index = 0; index < 8; index++) {
                    this.columns[index].show = false
                }
            } else {
                console.log("Bb");
                for (let index = 0; index < 8; index++) {
                    this.columns[index].show = true
                }
            }

            // console.log(v);
        },

        /*
         * 设计BOM的Excel导入
         */
        //分批导入
        handleBatchImport() {
            if (this.queryParam.moldCode) {
                if (this.selectedRowKeys.length > 0) {
                    let param = this.getQueryParams();
                    param['selections'] = this.selectedRowKeys.join(",")
                        //let param = this.selectedRowKeys
                    console.log("param", param);
                    console.log("this", this);
                    let _this = this
                    this.$confirm({
                        title: `模具编号：${this.queryParam.moldCode}`,
                        content: '确定分批导入当前选中的数据吗？',
                        // title: '确定分批导入当前选择的数据？',
                        // content: 'When clicked the OK button, this dialog will be closed after 1 second',
                        onOk() {
                            // 请求导入
                            getAction(_this.url.batchImportExcel, param).then(res => {
                                if (res) {
                                    console.log("res", res);
                                }
                                _this.loadData()
                            })
                            console.log("ok");
                        },
                        onCancel() {
                            console.log("Cancel");
                        },
                    });
                } else {
                    this.$message.warning("请选择分批导入的行！")
                }
            } else {
                this.$message.error("模具编码不能为空！")
            }

        },

        //全部导入
        handleAllImport() {

            /* 前端动态显示选中：
            1.向后端发起当前搜索栏结果的所有数据
            2.遍历并存放数据
            let selectedRowKeys = []
            let selectionRows = []
            this.dataSource.map((v, i) => {
                selectedRowKeys.push(v.id)
                selectionRows.push(v)
            })
            3.调用选中变化函数
            this.onSelectChange(selectedRowKeys, selectionRows)
            */

            /* 前端无动态显示
             * 后台直接做导出校验操作
             */
            if (this.queryParam.moldCode) {
                let _this = this
                this.$confirm({
                    title: `模具编号：${this.queryParam.moldCode}`,
                    content: '确定全部导入当前模具编号的所有数据吗？',
                    onOk() {
                        // 请求导入
                        getAction(_this.url.importAllExcel, _this.queryParam.moldCode).then(res => {
                            if (res) {
                                console.log("res", res);
                            }
                            _this.loadData()
                        })
                        console.log("ok");
                    },
                    onCancel() {
                        console.log("Cancel");
                    },
                });
                // 选中置空
                this.selectedRowKeys = []
            } else {
                this.$message.error("模具编码不能为空！")
            }


        },

        // 版本
        loadVersions() {
            //查询版本(请求获取)
            console.log('this.queryParam.moldCode', this.queryParam.moldCode)
            if (this.queryParam.moldCode) {
                this.versions = []
                getAction(this.url.queryVersions, {
                    moldCode: this.queryParam.moldCode
                }).then((res) => {
                    if (res.code == 200) {
                        if (res.result) {
                            res.result.forEach((item) => {
                                var obj = {}
                                obj.value = item
                                obj.text = item
                                this.versions.push(obj)
                            })
                        }
                        console.log('res111', res)
                        console.log('this.versions', this.versions)
                    } else {
                        // this.$message.error(res.message)
                        this.queryParam.version = ''
                        this.versions = []
                    }
                })
            } else {
                // this.$message.warning('模具编号不能为空')
                this.queryParam.version = ''
                this.versions = []
            }
        },
        // isVersions
        isVersions(value) {
            console.log('value', value);
            if (!value) {
                this.$message.warning('选择版本时模具编号不能为空')
            }
        },
        // moldCodeChange //清空时触发
        moldCodeChange() {
            if (this.queryParam.moldCode == null || this.queryParam.moldCode == undefined || this.queryParam.moldCode == '') {
                this.queryParam.version = ''
                this.versions = []
            }
        },
        //-------------------------------------------需求反馈管理系统
        //     // 获取系统名称,问题类型
        //    systemNameAndProblemType() {
        //     getAction(this.url.queryDistListByCode).then(res => {
        //         console.log("queryDistListByCode--res", res);
        //         if (res.code == 200) {
        //             // this.systemNames = res.result.system_code
        //             // this.problemTypes = res.result.problem_type
        //             // this.$emit('systemNames', res.result.system_code)
        //             // this.$emit('problemTypes', res.result.problem_type)
        //             if (res.result.system_code.length > 0 || res.result.problem_type.length >0) {
        //                 localStorage.setItem('systemNames',JSON.stringify(res.result.system_code))
        //                 localStorage.setItem('problemTypes',JSON.stringify(res.result.problem_type))
        //             }
        //         }
        //     })
        // },


        //-------------------------------------------周报记录
        //单个完成
        handleComplete(ids) {
            getAction('/ch/weeklyReportFeedback/completeBatch', { ids: ids }).then(res => {
                if (res.code == 200) {
                    this.$message.success("操作成功")
                    this.loadData()
                }
                console.log(res);
            })
        },

        //批量完成
        batchComplete() {
            // if (!this.url.deleteBatch) {
            //     this.$message.error("请设置url.deleteBatch属性!")
            //     return
            // }
            if (this.selectedRowKeys.length <= 0) {
                this.$message.warning('请选择一条记录！');
                return;
            } else {
                var ids = "";
                for (var a = 0; a < this.selectedRowKeys.length; a++) {
                    ids += this.selectedRowKeys[a] + ",";
                }
                var that = this;
                this.$confirm({
                    title: "确认完成",
                    content: "是否确认完成?",
                    onOk: function() {
                        that.loading = true;
                        getAction('/ch/weeklyReportFeedback/completeBatch', { ids: ids }).then((res) => {
                            if (res.success) {
                                //重新计算分页问题
                                that.reCalculatePage(that.selectedRowKeys.length)
                                that.$message.success(res.message);
                                that.loadData();
                                that.onClearSelected();
                            } else {
                                that.$message.warning(res.message);
                            }
                        }).finally(() => {
                            that.loading = false;
                        });
                    }
                });
            }
        },

        // ------------------------------------------HUB仓
        // 环境准备
        // environmentPreparation() {
        //     var params = this.queryParam
        //     console.log('params', params);
        //     getAction(this.url.exportHubList, params).then((res) => {
        //         console.log('this', this);
        //         // alert("111")
        //         this.$message.warning(res.message)
        //         console.log("res1111:", res);
        //     })
        // },
        initDictConfig() {
            console.log("--这是一个假的方法!")
        },
        handleSuperQuery(params, matchType) {
            //高级查询方法
            if (!params) {
                this.superQueryParams = ''
                this.superQueryFlag = false
            } else {
                this.superQueryFlag = true
                this.superQueryParams = JSON.stringify(params)
                this.superQueryMatchType = matchType
            }
            this.loadData(1)
        },
        getQueryParams() {

            //获取查询条件
            let sqp = {}
            if (this.superQueryParams) {
                sqp['superQueryParams'] = encodeURI(this.superQueryParams)
                sqp['superQueryMatchType'] = this.superQueryMatchType
            }
            // let data = Json.parse(localStorage.getItem('data'))
            // console.log("\\\\\\\\\\",localStorage.getItem('data').parseJSON);
            var param = Object.assign(sqp, this.queryParam, this.filters);
            console.log("aa", window.localStorage.getItem('data'));
            if (localStorage.getItem('data') != '') {
                param.id = window.localStorage.getItem('data')
                    // this.queryParam.itemName = window.localStorage.getItem('data')
                console.log("param.id", param.id);
            }
            if (localStorage.getItem('dataId') != '') {
                param.id = window.localStorage.getItem('dataId')
            }
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.pageSize = this.ipagination.pageSize;
            console.log("param", param);

            window.localStorage.removeItem('data')
            window.localStorage.removeItem('dataId')
                // this.$bus.$on('record', (record) => {
                //     console.log('record111---------------', record);
                //     if (record.itemName) {
                //         this.queryParam = record
                //         console.log('this.queryParam.itemName111',this.queryParam.itemName);
                //     }
                // })
                // console.log("this.queryParam111111111111111111", this.queryParam);

            // var param = Object.assign(sqp,this.queryParam, this.filters);
            // param.field = this.getQueryField();
            // param.itemName = this.queryParam.itemName
            // param.pageNo = this.ipagination.current;
            // param.pageSize = this.ipagination.pageSize;

            // this.$bus.$on('record', (record) => { 
            //     console.log('record111---------------', record);
            //     // if (record.itemName) {
            //         param = Object.assign(sqp, {itemName:record.itemName}, this.filters);
            //         param.field = this.getQueryField();
            //         param.pageNo = this.ipagination.current;
            //         param.pageSize = this.ipagination.pageSize;
            //         // return filterObj(param);
            //         // this.queryParam = record
            //         // console.log('this.queryParam.itemName111',this.queryParam.itemName);
            //     // }
            // })

            return filterObj(param);


        },
        getQueryField() {
            //TODO 字段权限控制
            var str = "id,";
            this.columns.forEach(function(value) {
                str += "," + value.dataIndex;
            });
            return str;
        },

        onSelectChange(selectedRowKeys, selectionRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectionRows = selectionRows;
            console.log('this.selectedRowKeys', this.selectedRowKeys);
            console.log('this.selectionRows', this.selectionRows);
        },
        onClearSelected() {
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        searchQuery() {
            this.loadData(1);
            // 点击查询清空列表选中行
            // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
            this.selectedRowKeys = []
            this.selectionRows = []
        },
        superQuery() {
            this.$refs.superQueryModal.show();
        },
        searchReset() {
            this.queryParam = {}
            this.versions = []
            this.loadData(1);
        },
        batchDel: function() {
            console.log(this.url.deleteBatch)
            if (!this.url.deleteBatch) {
                this.$message.error("请设置url.deleteBatch属性!")
                return
            }
            if (this.selectedRowKeys.length <= 0) {
                this.$message.warning('请选择一条记录！');
                return;
            } else {
                var ids = "";
                for (var a = 0; a < this.selectedRowKeys.length; a++) {
                    ids += this.selectedRowKeys[a] + ",";
                }
                var that = this;
                this.$confirm({
                    title: "确认删除",
                    content: "是否删除选中数据?",
                    onOk: function() {
                        that.loading = true;
                        deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
                            if (res.success) {
                                //重新计算分页问题
                                that.reCalculatePage(that.selectedRowKeys.length)
                                that.$message.success(res.message);
                                that.loadData();
                                that.onClearSelected();
                            } else {
                                that.$message.warning(res.message);
                            }
                        }).finally(() => {
                            that.loading = false;
                        });
                    }
                });
            }
        },
        toImgPri: function() {
            // if (!this.url.generatePrintData) {
            //     this.$message.error("请设置url.generatePrintData属性!")
            //     return
            // }   
            if (this.selectedRowKeys.length > 1) {
                this.$message.warning("只能选择一条记录！")
                return;
            }
            if (this.selectedRowKeys.length <= 0) {
                this.$message.warning('请选择一条记录！');
                return;
            } else {
                var ids = "";
                for (var a = 0; a < 1; a++) {
                    ids += this.selectedRowKeys[a];
                }
                var that = this;
                this.$confirm({
                    title: "确认打印",
                    content: "是否打印选中数据?",
                    onOk: function() {
                        that.loading = true;
                        printAction(that.url.print, { ids: ids }).then((res) => {
                            if (res.success) {
                                //重新计算分页问题
                                that.reCalculatePage(that.selectedRowKeys.length)
                                that.$message.success("打印成功！");
                                that.loadData();
                                that.onClearSelected();
                            } else {
                                that.$message.warning(res.message);
                            }
                        }).finally(() => {
                            that.loading = false;
                        });
                    }
                });
            }
        },
        // ""
        handleDelete: function(id) {
            if (!this.url.delete) {
                this.$message.error("请设置url.delete属性!")
                return
            }
            var that = this;
            deleteAction(that.url.delete, { id: id }).then((res) => {
                if (res.success) {
                    //重新计算分页问题
                    that.reCalculatePage(1)
                    that.$message.success(res.message);
                    that.loadData();
                } else {
                    that.$message.warning(res.message);
                }
            });
        },
        reCalculatePage(count) {
            //总数量-count
            let total = this.ipagination.total - count;
            //获取删除后的分页数
            let currentIndex = Math.ceil(total / this.ipagination.pageSize);
            //删除后的分页数<所在当前页
            if (currentIndex < this.ipagination.current) {
                this.ipagination.current = currentIndex;
            }
            console.log('currentIndex', currentIndex)
        },
        handleEdit: function(record) {
            console.log("1111", record);
            localStorage.setItem('feedRecord', JSON.stringify(record))
            record.allocator = record.allocatorList
            console.log("this.$refs.modalForm", this.$refs.modalForm);
            this.$refs.modalForm.edit(record);
            this.$refs.modalForm.title = "编辑";
            this.$refs.modalForm.disableSubmit = false;
        },
        rowClick(record, index) {
            return {
                on: {
                    // click: () => {
                    //   console.log("record:", record);
                    //   console.log("index:", index);
                    // },

                    dblclick: () => {
                        console.log("双击");
                        console.log("record:", record);
                        console.log("index:", index);
                        this.$router.push('/ChSoftwareOperationPlanList')
                            //   this.handleEdit(record)
                    }

                }

            }

        },
        handleAdd: function(data) {
          console.log('自定义方法进来了,data',data);
          console.log('this.$refs.modalForm之后',this.$refs);
            if (data == '会议') {
                getAction('/ch/weeklyReportFeedback/generateWeeklyTitle').then((res) => {
                    console.log("generateWeeklyTitle:", res);
                    localStorage.setItem('generateWeeklyTitle', (res.message))
                })
            }
            // if (data == '系统问题分配') {
            //     this.systemNameAndProblemType()
            // }
            this.$refs.modalForm.add();
            this.$refs.modalForm.title = "新增";
            this.$refs.modalForm.disableSubmit = false;
        },
        handleAdd2() {
            // postAction(this.url.add, {}).then(res => {
            //     if (res) {
            //         console.log("add-res:", res);
            //     }
            //     this.loadData()
            // })
            console.log('this.queryParam.moldCode', this.queryParam.moldCode);
            if (this.queryParam.moldCode == '' || this.queryParam.moldCode == undefined) {
                this.$message.error('查询中的模具编号不能为空');
                return
            }
            this.ipagination.current = this.ipagination.total % this.ipagination.pageSize == 0 ? (this.ipagination.total / this.ipagination.pageSize) + 1 : Math.ceil(this.ipagination.total / this.ipagination.pageSize);
            console.log('this.ipagination.current', this.ipagination.current);
            this.loadData();
            httpAction(this.url.add, { moldCode: this.queryParam.moldCode }, 'post').then((res) => {
                if (res.success) {
                    console.log("add-res:", res);
                    this.$message.success(res.message);
                    this.$emit('ok');
                    this.loadData();
                } else {
                    this.$message.warning(res.message);
                }
            })
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            console.log("pagination:", pagination)
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field;
                this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
            }
            this.ipagination = pagination;
            this.loadData();
        },
        handleToggleSearch() {
            this.toggleSearchStatus = !this.toggleSearchStatus;
        },
        // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
        getPopupField(fields) {
            return fields.split(',')[0]
        },
        modalFormOk() {
            // 新增/修改 成功时，重载列表
            this.loadData();
            //清空列表选中
            this.onClearSelected()
        },
        handleDetail: function(record) {
            this.$refs.modalForm.edit(record);
            this.$refs.modalForm.title = "详情";
            this.$refs.modalForm.disableSubmit = true;
        },
        /* 导出 */
        handleExportXls2() {
            let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));
            let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;
            window.location.href = url;
        },
        // 联想导出
        lxHandleExportXls(e) {
            console.log(e.key);
            let param = this.getQueryParams();
            param.printLocation = e.key
            if (this.selectedRowKeys.length != 1) {
                this.$message.error("请选择要导出的一条数据")
                return
            }
            // param['selections'] = this.selectedRowKeys
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) { param['selections'] = this.selectedRowKeys.join(",") }
            console.log("导出参数", param)
            downFile(this.url.exportXlsUrl2, param).then((data) => {
                if (!data) {
                    this.$message.warning("文件导出失败！")
                    return
                }
                this.$message.success("文件导出成功！")
            })
        },
        handleExportXls(fileName) {
            if (!fileName || typeof fileName != "string") {
                fileName = "导出文件"
            }
            let param = this.getQueryParams();
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
                param['selections'] = this.selectedRowKeys.join(",")
            }
            console.log("导出参数", param)
                // 判断路径
            if (this.url.exportXlsUrl == '/ch/chDesignBomMaster/exportXls' ||
                this.url.exportXlsUrl == '/ch/chDesignBomExcel/exportXls' ||
                this.url.exportXlsUrl == '/ch/chDesignBom/exportXls' ||
                this.url.exportXlsUrl == '/ch/chOrderBom/exportXls') {
                if (this.queryParam.moldCode) {
                    downFile(this.url.exportXlsUrl, param).then((data) => {
                        if (!data) {
                            this.$message.warning("文件导出失败")
                            return
                        }
                        if (typeof window.navigator.msSaveBlob !== 'undefined') {
                            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '-' + this.queryParam.moldCode + '.xls')
                            this.$message.success("文件导出成功")
                        } else {
                            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                            let link = document.createElement('a')
                            link.style.display = 'none'
                            link.href = url
                            link.setAttribute('download', fileName + '-' + this.queryParam.moldCode + '.xls')
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link); //下载完成移除元素
                            window.URL.revokeObjectURL(url); //释放掉blob对象
                            this.$message.success("文件导出成功")
                        }

                    })
                } else {
                    this.$message.error("导出时模具编号不能为空！")
                }

            } else {
                downFile(this.url.exportXlsUrl, param).then((data) => {
                    if (!data) {
                        this.$message.warning("文件导出失败")
                        return
                    }
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {

                        window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '-' + this.queryParam.moldCode + '.xls')
                        this.$message.success("文件导出成功")
                    } else {
                        let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                        let link = document.createElement('a')
                        link.style.display = 'none'
                        link.href = url
                        link.setAttribute('download', fileName + '.xls')
                        document.body.appendChild(link)
                        link.click()
                        document.body.removeChild(link); //下载完成移除元素
                        window.URL.revokeObjectURL(url); //释放掉blob对象
                        this.$message.success("文件导出成功")
                    }

                })
            }

        },
        // hub仓导出
        handleExportXlsHub(fileName) {
            if (!fileName || typeof fileName != "string") {
                fileName = "导出文件"
            }
            let param = this.getQueryParams();
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
                param['selections'] = this.selectedRowKeys.join(",")
            }
            console.log("导出参数", param)
            this.spinning = !this.spinning;
            downFile(this.url.exportXlsUrl, param).then((data) => {
                this.spinning = !this.spinning;
                if (!data) {
                    this.$message.warning("文件导出失败")
                    return
                }
                if (typeof window.navigator.msSaveBlob !== 'undefined') {

                    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '-' + this.queryParam.moldCode + '.xlsx')
                    this.$message.success("文件导出成功")

                } else {

                    let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + '.xlsx')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link); //下载完成移除元素
                    window.URL.revokeObjectURL(url); //释放掉blob对象
                    this.$message.success("文件导出成功")
                }

            })
        },
        //设计BOM导出
        handleExportXlsDesignBom(fileName) {
            if (!fileName || typeof fileName != "string") {
                fileName = "导出文件"
            }
            let param = this.getQueryParams();
            if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
                param['selections'] = this.selectedRowKeys.join(",")
            }
            console.log("导出参数", param)
            downFile(this.url.exportXlsUrl, param).then((data) => {


                if (!data) {
                    this.$message.warning("文件导出失败")
                    return
                }
                if (data instanceof Blob) {
                    var blob = data

                    // 通过FileReader读取数据
                    var reader = new FileReader()

                    reader.readAsBinaryString(blob)

                    console.log('blob:', blob);
                }

                this.$message.success("文件导出成功！")
            })
        },
          /* 现行设备转报废 */
        handleTransferToScrap: function(record) {
          // 先删除
          this.handleDelete(record.id);
            //跳转到报废品管理界面 
            this.$router.push('/ScrapManagementList')
            // this.$nextTick(function () {
              //将数据传到ScrapManagementList并让ScrapManagementList调用add方法
              // this.$bus.$emit('ChCurrentEquipmentManagementRecord', record)
              console.log('触发了ChCurrentEquipmentManagementRecord');
               //定义缓存的对象
               let scrapManagement = {}
               scrapManagement.id = record.id
               scrapManagement.name = record.name
               scrapManagement.type = record.type
               scrapManagement.status = record.status
               scrapManagement.quantity = record.quantity
               scrapManagement.equipmentManager = record.equipmentManager
               scrapManagement.equipmentFixedAssetNo = record.equipmentFixedAssetNo
               scrapManagement.itAssetNumber = record.itAssetNumber
               scrapManagement.equipmentPurchaseDate = record.equipmentPurchaseDate
               scrapManagement.remark = record.remark
               scrapManagement.entryTime = record.entryDate
               scrapManagement.enteredBy = record.enteredBy
               localStorage.setItem('scrapManagement', JSON.stringify(scrapManagement))
            //  })
      },

           /* 备品备件转报废 */
           handleTransferToScrap2: function(record) {
            // 先删除
            this.handleDelete(record.id);
              //跳转到报废品管理界面 
              this.$router.push('/ScrapManagementList')
              // this.$nextTick(function () {
                //将数据传到ScrapManagementList并让ScrapManagementList调用add方法
                // this.$bus.$emit('ChCurrentEquipmentManagementRecord', record)
                console.log('触发了ChCurrentEquipmentManagementRecord');
                 //定义缓存的对象
                 let scrapManagement = {}
                 scrapManagement.id = record.id
                 scrapManagement.name = record.name
                 scrapManagement.type = record.type
                 scrapManagement.status = record.state
                 scrapManagement.quantity = record.quantity
                 scrapManagement.equipmentManager = record.equipmentManager
                 scrapManagement.equipmentFixedAssetNo = record.equipmentFixedAssetNo
                 scrapManagement.itAssetNumber = record.itAssetNumber
                 scrapManagement.equipmentPurchaseDate = record.equipmentPurchaseDate
                 scrapManagement.remark = record.remarks
                 scrapManagement.entryTime = record.entryTime
                 scrapManagement.enteredBy = record.enteredBy
                 localStorage.setItem('scrapManagement', JSON.stringify(scrapManagement))
              //  })
        },
     

        /* 导入 */
        handleImportExcel(info) {
            console.log('info', info);
            this.loading = true;
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                this.loading = false;
                if (info.file.response.success) {
                    // this.$message.success(`${info.file.name} 文件上传成功`);
                    if (info.file.response.code === 201) {
                        let { message, result: { msg, fileUrl, fileName } } = info.file.response
                        let href = window._CONFIG['domianURL'] + fileUrl
                        this.$warning({
                            title: message,
                            content: ( < div >
                                <
                                span > { msg } < /span><br / >
                                <
                                span > 具体详情请 < a href = { href }
                                target = "_blank"
                                download = { fileName } > 点击下载 < /a> </span >
                                <
                                /div>
                            )
                        })
                    } else {
                        this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
                    }
                    this.loadData()
                } else {
                    this.$message.error(`${info.file.name} ${info.file.response.message}.`);
                }
            } else if (info.file.status === 'error') {
                this.loading = false;
                if (info.file.response.status === 500) {
                    let data = info.file.response
                    const token = Vue.ls.get(ACCESS_TOKEN)
                    if (token && data.message.includes("Token失效")) {
                        this.$error({
                            title: '登录已过期',
                            content: '很抱歉，登录已过期，请重新登录',
                            okText: '重新登录',
                            mask: false,
                            onOk: () => {
                                store.dispatch('Logout').then(() => {
                                    Vue.ls.remove(ACCESS_TOKEN)
                                    window.location.reload();
                                })
                            }
                        })
                    }
                } else {
                    this.$message.error(`文件上传失败: ${info.file.msg} `);
                }
            }
        },
        handleImportExcel1(info) {
            console.log('info', info);
            this.loading = true;
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                this.loading = false;
                if (info.file.response.success) {
                    // this.$message.success(`${info.file.name} 文件上传成功`);
                    if (info.file.response.code === 201) {
                        let { message, result: { msg, fileUrl, fileName } } = info.file.response
                        let href = window._CONFIG['domianURL'] + fileUrl
                        this.$warning({
                            title: message,
                            content: ( < div >
                                <
                                span > { msg } < /span><br / >
                                <
                                span > 具体详情请 < a href = { href }
                                target = "_blank"
                                download = { fileName } > 点击下载 < /a> </span >
                                <
                                /div>
                            )
                        })
                    } else {
                        this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
                    }

                } else {
                    this.$message.error(`${info.file.name} ${info.file.response.message}.`);
                }
            } else if (info.file.status === 'error') {
                this.loading = false;
                if (info.file.response.status === 500) {
                    let data = info.file.response
                    const token = Vue.ls.get(ACCESS_TOKEN)
                    if (token && data.message.includes("Token失效")) {
                        this.$error({
                            title: '登录已过期',
                            content: '很抱歉，登录已过期，请重新登录',
                            okText: '重新登录',
                            mask: false,
                            onOk: () => {
                                store.dispatch('Logout').then(() => {
                                    Vue.ls.remove(ACCESS_TOKEN)
                                    window.location.reload();
                                })
                            }
                        })
                    }
                } else {
                    this.$message.error(`文件上传失败: ${info.file.msg} `);
                }
            }
        },
        /* 图片预览 */
        getImgView(text) {
            if (text && text.indexOf(",") > 0) {
                text = text.substring(0, text.indexOf(","))
            }
            return getFileAccessHttpUrl(text)
        },
        /* 文件下载 */
        // update--autor:lvdandan-----date:20200630------for：修改下载文件方法名uploadFile改为downloadFile------
        downloadFile(text) {
            console.log(text)
            if (!text) {
                this.$message.warning("未知的文件")
                return;
            }
            if (text.indexOf(",") > 0) {
                text = text.substring(0, text.indexOf(","))
            }
            let url = getFileAccessHttpUrl(text)
            window.open(url);
        },
    }

}